<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :row-class-name="tableRowClassName"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menu" slot-scope="{ row }">
        <!-- <el-button size="small" type="text" @click="handleIqcExamine(row)">检验（临时方案）</el-button> -->
        <el-button size="small" type="text" v-if="permission.incomingMaterialsToBeInspected_executeInspection" @click="handleExecuteInspection(row)">检验</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" v-if="permission.incomingMaterialsToBeInspected_merge" @click="mergeCheck()">合并检验</el-button>
        <el-button size="small" type="primary" v-if="permission.incomingMaterialsToBeInspected_urgent" @click="handleUrgent()">加急</el-button>
      </template>
    </avue-crud>
    <!-- 待检单合并 -->
    <el-dialog append-to-body :close-on-click-modal="false" title="待检单合并" :visible.sync="mergeDialog" @close="mergeClose" width="60%">
      <avue-crud v-if="mergeDialog" ref="mergeCrud" :option="mergeOption" :data="mergeData"></avue-crud>
      <span slot="footer" class="dialog-footer merge">
        <el-button size="small" type="primary" @click="mergeSubmit()"> <i class="el-icon-circle-plus-outline"></i><span>合 并</span> </el-button>
        <el-button size="small" @click="mergeDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <!--执行检验弹窗-->
    <el-dialog
      v-if="executeInspectionDialog"
      fullscreen
      append-to-body
      :modal-append-to-body="true"
      :close-on-click-modal="false"
      title="执行检验"
      :visible.sync="executeInspectionDialog"
    >
      <execute-inspection @closeDialog="exeInspectionCloseDialog" :liveParams="liveParams" v-if="executeInspectionDialog" ref="executeInspection"></execute-inspection>
    </el-dialog>
    <handle-iqc-inspection ref="iqcInspection" @sumbit="handleReportSubmit" :visible.sync="iqcInspectionVisible"></handle-iqc-inspection>
    <!--公用模态弹框-->
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, mergeCheck, urgent, getConfigTemplate } from '@/api/quality/incomingMaterialsToBeInspected';
import { mapGetters } from 'vuex';
import userConfig from '@/mixins/userConfig';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import executeInspection from '@/views/designer/preview';
import handleIqcInspection from '@/views/quality/refactor/components/handleIqcInspection';
export default {
  components: {
    commonModalTemplate,
    executeInspection,
    handleIqcInspection
  },
  mixins: [userConfig()],
  data() {
    return {
      iqcInspectionVisible: false,
      executeInspectionDialog: false,
      fullscreenDialog: false, //dialog是否全屏
      pageCode: 'IQC_EXAMINE',
      form: {},
      model: {},
      loading: true,
      page: {
        pageSize: 15,
        currentPage: 1,
        total: 0
      },
      liveParams: {
        documentNo: '',
        documentType: ''
      },
      selectionList: [],
      data: [],
      timerId: null,
      searchLabelWidth: 100,
      option: {
        height: 'calc(100vh - 400px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        searchLabelWidth: 90,
        menuWidth: 100,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'examineNo',
            search: true
          },
          {
            label: '收料通知单',
            prop: 'erpReferenceNo',
            search: true
          },
          // {
          //   label: '单据号',
          //   prop: 'purchaseOrderNo',
          //   search: true
          // },
          {
            label: '送检日期',
            prop: 'sendExamineTime',
            search: true,
            searchOrder: 20,
            searchSpan: 6,
            type: 'date',
            searchType: 'datetimerange',
            order: 18,
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '物料编码',
            prop: 'partNo',
            search: true
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partSpec'
          },
          {
            label: '收料数量',
            prop: 'sendExamineQuantity'
          },
          {
            label: '是否加急',
            prop: 'isUrgent',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '供应商代码',
            search: true,
            prop: 'vendorCode'
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          // {
          //   label: '收料单号',
          //   prop: 'receiveNo',
          //   width: 150,
          //   search: true
          // },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          // {
          //   label: '检验批次',
          //   prop: 'inspectionLotNo'
          // },
          {
            label: '检验方式',
            prop: 'examineMode',
            order: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '检验负责人',
            prop: 'principalName',
            search: true
          }
        ]
      },
      mergeDialog: false,
      mergeOption: {
        height: 'calc(100vh - 486px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: false,
        refreshBtn: false,
        menu: false,
        dialogClickModal: false,
        labelWidth: 120,
        searchMenuSpan: 12,
        searchMenuPosition: 'right',
        searchLabelWidth: 90,
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'examineNo'
          },
          {
            label: '单据号',
            prop: 'purchaseOrderNo'
          },
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: '收料数量',
            prop: 'sendExamineQuantity'
          },
          {
            label: '是否加急',
            prop: 'isUrgent',
            type: 'switch',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '供应商代码',
            prop: 'vendorCode'
          },
          {
            label: '供应商名称',
            prop: 'vendorName'
          },
          {
            label: '供应商批次',
            prop: 'vendorLotNo'
          },
          // {
          //   label: '检验批次',
          //   prop: 'inspectionLotNo'
          // },
          {
            label: '检验人员',
            prop: 'examineByName'
          }
        ]
      },
      timer: new Date().getTime()
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    async handleIqcExamine(row) {
      this.iqcInspectionVisible = true;
      await this.$refs.iqcInspection.setForm(row);
    },
    handleReportSubmit() {
      this.iqcInspectionVisible = false;
      this.onLoad(this.page);
    },
    exeInspectionCloseDialog() {
      this.executeInspectionDialog = false;
      this.onLoad(this.page);
    },
    handleExecuteInspection(row) {
      getConfigTemplate({
        inspectionType: 'IQC',
        partMasterId: row.partMasterId,
        vendorId: row.vendorId
      }).then((res) => {
        let data = res.data.data;
        if (!data.apaasTemplateId) {
          this.$message({
            type: 'warning',
            message: `${row.partNo}（物料编码）没有配置检验模板，请先进行配置！`
          });
          return;
        }
        this.liveParams.documentNo = row.examineNo;
        this.liveParams.documentType = 'IQC';
        this.executeInspectionDialog = true;
        this.$nextTick(() => {
          this.$refs.executeInspection.viewApaasTemplate(data.apaasTemplateId);
        });
      });
    },
    handleUrgent() {
      if (this.selectionList.length === 0) {
        this.$message({
          type: 'warning',
          message: '请选择检验单!'
        });
        return;
      }
      this.$confirm('确认对检验单进行加急?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.ids, 88888);
          return urgent(this.ids)
            .then((res) => {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
            })
            .catch((err) => {});
        })
        .then(() => {
          this.onLoad(this.page);
          this.$refs.crud.toggleSelection();
        });
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.isUrgent) {
        return 'urgent-select-row';
      }
      return '';
    },
    beforeOpen(done, type) {
      // if (['edit', 'view'].includes(type)) {
      //   getDetail(this.form.id).then((res) => {
      //     this.form = res.data.data;
      //   });
      // }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.sendExamineTime && params.sendExamineTime.length > 0) {
        params.sendStartTime = params.sendExamineTime[0];
        params.sendEndTime = params.sendExamineTime[1];
      }
      delete params.sendExamineTime;
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    closeDialog() {
      // if (this.basicInfoForm.examineMode === 'SAMPLING') {
      this.$refs.sampleInfoForm.resetFields();
      this.sampleInfoForm = {};
      this.newKey();
      // }
      this.$refs.basicInfoForm.resetFields();
      this.basicInfoForm = {};
      this.$refs.inspectionResultsRecordForm.resetFields();
      this.inspectionResultsRecordForm = {};
      this.failureRecordData = [];
    },
    /*
     * 合并检验
     */
    mergeCheck() {
      if (this.selectionList.length < 2) {
        this.$message({
          type: 'warning',
          message: '请选择至少两条检验单!'
        });
        return;
      }
      if (!this.areFieldsConsistent(this.selectionList)) {
        this.$message({
          type: 'warning',
          message: `选中的检验单号${this.selectionList.map((item) => item.examineNo).join(',')}中存在（供应商、内部批次、物料编码）不相同的情况，请检查！`
        });
        return;
      }
      let row = this.selectionList[0];
      getConfigTemplate({
        inspectionType: 'IQC',
        partMasterId: row.partMasterId,
        vendorId: row.vendorId
      }).then((res) => {
        let data = res.data.data;
        if (!data.apaasTemplateId) {
          this.$message({
            type: 'warning',
            message: `${row.partNo}（物料编码）没有配置检验模板，请先进行配置！`
          });
          return;
        }
        this.liveParams.documentNo = this.selectionList.map((item) => item.examineNo).join(',');
        this.liveParams.documentType = 'IQC';
        this.executeInspectionDialog = true;
        this.$nextTick(() => {
          this.$refs.executeInspection.viewApaasTemplate(data.apaasTemplateId);
        });
      });
    },
    /**
     * 判断数据对象中是否所有记录的供应商、物料编码和内部批次一致
     * @param {Object[]} data - 数据对象数组
     * @returns {boolean} - 返回是否所有记录的三个字段一致
     */
    areFieldsConsistent(data) {
      // 获取第一条记录的基准值
      const { vendorName, partNo, lotNo } = data[0];
      // 检查是否所有记录的三个字段都一致
      return data.every((item) => {
        console.log(item.vendorName == vendorName && item.partNo == partNo && item.lotNo == lotNo);
        return item.vendorName == vendorName && item.partNo == partNo && item.lotNo == lotNo;
      });
    },
    mergeSubmit() {
      mergeCheck(this.ids).then((res) => {
        this.mergeDialog = false;
        this.$message.success(res.data.msg);
        this.onLoad(this.page);
      });
    },
    mergeClose() {
      this.mergeData = [];
    },
    openUserCommonModal() {
      this.modalName = 'userModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择检验人员信息（双击进行选择）',
        url: '/api/blade-user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    openFailureCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'failureModal';
      this.tableOption = {
        modalTitle: '不良现象（双击进行选择）',
        url: '/api/mes-qms/mro/dict/page?dictType=FAILURE',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '不良代码',
            prop: 'code',
            search: true
          },
          {
            label: '不良现象描述',
            prop: 'name'
          }
        ]
      };
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'userModal':
          this.basicInfoForm.examineBy = rowData.id;
          this.basicInfoForm.examineByName = rowData.realName;
          break;
        case 'failureModal':
          this.addFailureRecordForm.failureId = rowData.id;
          this.addFailureRecordForm.failureCode = rowData.code;
          this.addFailureRecordForm.failureName = rowData.name;
          break;
        default:
          break;
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}
.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
  ::v-deep .el-form-item__label {
    font-weight: bold;
    font-size: 16px;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
::v-deep .urgent-select-row {
  color: red;
}
.groups {
  margin: 10px 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #dedede;
  .titleIcon {
    display: flex;
    align-items: center;
  }
}
.aqlValueDialog {
  ::v-deep .el-form-item__content {
    line-height: 33px;
  }
}

.title-result {
  display: flex;
  justify-content: space-between;
  .title {
    display: flex;
    align-items: center;
  }
  .reslut-btn-group {
    margin-right: 8px;
  }
}
.download-box {
  .dowload-item {
    margin: 4px 8px;
    color: #007dff;
    -webkit-user-select: none; /* Safari */
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* Internet Explorer/Edge */
    user-select: none;
    &:hover {
      cursor: pointer;
    }
  }
}
.template-label {
  display: flex;
  flex-direction: row;
}
.dialog-title {
  position: relative;
  .title {
    display: inline-block;
  }
  .fullscreen-icon {
    position: absolute;
    right: 20px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    color: #909399;
    &:hover {
      color: #0a84ff;
    }
  }
}

.fullscreen {
  ::v-deep .el-dialog {
    width: 100%;
    margin: 0 !important;
    margin-top: 0vh !important;
  }
}
.no_fullScreen {
  ::v-deep.el-dialog {
    width: 50%;
    margin-top: 5vh !important;
  }
}
</style>
